<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">+新增</el-button>

    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input v-model="formInline.keyword" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSerch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="(item, index) in tableLabel"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width ? item.width : 125"
      />
      <el-table-column width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="prev, pager, next,jumper"
      :total="config.total"
      size="small"
      @current-change="pageChange"
      @size-change="sizeChange"
      v-model:page-size="config.sizePage"
    />
  </div>

  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
    :before-close="handleClose"
  >
    <!--需要注意的是设置了:inline="true"，
		会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
		在css进行处理-->
    <el-form :inline="true" :model="formUser" :rules="rules" ref="userFormRef">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              placeholder="请输入"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue'
import { getUserData, deleteUser, addUser, editUser } from '../api/api'
const { proxy } = getCurrentInstance()
const userFormRef = ref('')

const formInline = reactive({
  keyword: ''
})
const list = ref([])
const tableLabel = reactive([
  {
    prop: 'name',
    label: '姓名'
  },
  {
    prop: 'age',
    label: '年龄'
  },
  {
    prop: 'sexLabel',
    label: '性别'
  },
  {
    prop: 'birth',
    label: '出生日期',
    width: 200
  },
  {
    prop: 'addr',
    label: '地址',
    width: 400
  }
])
const tableData = ref([])

const config = reactive({
  name: '',
  total: 0,
  page: 1,
  sizePage: 1
})
//控制对话框是否显示
const dialogVisible = ref(false)

//新增和编辑共用一个窗口，所以通过设置action区分
const action = ref('add')

const formUser = reactive({})
//表单校验规则
const rules = reactive({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    { type: 'number', message: '年龄必须是数字' }
  ],
  sex: [{ required: true, message: '性别是必选项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必选项' }],
  addr: [{ required: true, message: '地址是必填项' }]
})

const timeFormat = time => {
  var time = new Date(time)
  var year = time.getFullYear()
  var month = time.getMonth() + 1
  var date = time.getDate()
  function add (m) {
    return m < 10 ? '0' + m : m
  }
  return year + '-' + add(month) + '-' + add(date)
}

const handleEdit = val => {
  action.value = 'edit'
  dialogVisible.value = true
  // nextTick 解决编辑回显会影响新增同步回显编辑内容的bug
  nextTick(() => {
    // formUser.name = val.name
    // formUser.age = val.age
    // formUser.sex = '' + val.sex
    // formUser.birth = val.birth
    // formUser.addr = val.addr

    Object.assign(formUser, { ...val, sex: '' + val.sex })
  })

  getUserDataFn()
}

const getUserDataFn = async () => {
  let res = await getUserData(config)
  tableData.value = res.list.map(item => {
    return {
      ...item,
      sexLabel: item.sex === 1 ? '男' : '女'
    }
  })

  config.total = res.count
}
onMounted(() => {
  getUserDataFn()
})

const handleAdd = () => {
  action.value = 'add'
  dialogVisible.value = true
}
const handleClose = () => {
  //获取到表单dom，执行resetFields重置表单
  // proxy.$refs['userFormRef'].resetFields()
  userFormRef.value.resetFields()
  dialogVisible.value = false
}

const handleCancel = () => {
  proxy.$refs['userFormRef'].resetFields()
  dialogVisible.value = false
}
const onSubmit = () => {
  proxy.$refs['userFormRef'].validate(async valid => {
    //如果校验成功
    if (valid) {
      let res = null
      formUser.birth = timeFormat(formUser.birth)
      if (action.value === 'add') {
        res = await addUser(formUser)
      } else if (action.value === 'edit') {
        res = await editUser(formUser)
      }
      if (res) {
        //关闭对话框，重置表单，重新请求用户数据
        dialogVisible.value = false
        proxy.$refs['userFormRef'].resetFields()
        getUserDataFn()
      }

      //如果校验失败
    } else {
      ElMessage({
        showClose: true,
        message: '请输入正确的内容',
        type: 'error'
      })
    }
  })
}

const handleSerch = () => {
  config.name = formInline.keyword
  getUserDataFn(config)
}

const pageChange = page => {
  config.page = page
  getUserDataFn()
}
const sizeChange = page => {
  config.sizePage = page
  getUserDataFn()
}

const handleDelete = val => {
  console.log('val', val.id)

  //如果选择确定，就会执行then中的方法
  ElMessageBox.confirm('你确定删除吗?', {
    cancelButtonText: '取消',
    confirmButtonText: '确定'
  }).then(async () => {
    await deleteUser({ id: val.id })

    //删除成功后弹出一个提示框
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success'
    })
    getUserDataFn()
  })
}
</script>

<style lang="scss" scoped>
.user-header {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 10px;
    bottom: 30px;
  }
  .el-table {
    width: 100%;
    height: 500px;
  }
}
.select-clearn {
  display: flex;
}
.pageTable {
  height: 50px;
}
</style>
